package com.googlecode.lookie.platform.image.io;

import java.awt.Image;
import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.googlecode.lookie.platform.image.resource.Resource;
import com.googlecode.lookie.platform.image.resource.ResourceException;

public abstract class AbstractReader
    implements Reader
{

    private Logger logger;

    protected AbstractReader()
    {
        this( LoggerFactory.getLogger( AbstractReader.class ) );
    }

    protected AbstractReader( Logger logger )
    {
        this.logger = logger;
    }

    protected Logger getLogger()
    {
        return logger;
    }

    public Image read( Resource resource )
        throws ReaderException
    {

        InputStream is = null;

        try
        {
            is = resource.createInputStream();
        }
        catch ( ResourceException e )
        {
            throw new ReaderException( e );
        }

        Image image = null;

        try
        {

            try
            {
                image = doRead( is );
            }
            catch ( Exception e )
            {
                throw new ReaderException( e );
            }
        }
        finally
        {

            if ( is != null )
            {
                try
                {
                    is.close();
                }
                catch ( IOException e )
                {
                    getLogger().warn( "error closing input stream on ", e );
                }
            }
        }

        return image;
    }

    protected abstract Image doRead( InputStream is )
        throws Exception;
}
